import http from '../http.js'
import store from '@/store/index.js'

WeiXinGetCode()
// 用户登录
function login(){
	WeiXinGetCode()
	return new Promise((resolve,reject) => {
		// 调用微信接口获取用户信息
		WeiXinRequestLogin()
		.then(res => {
			const dat = {
				code:store.state.user.code,	// 临时code
				signature:res.signature,	// 校验码
				encryptedData:res.encryptedData,// 加密数据
				iv:res.iv,					// iv
				rawData:res.rawData			// 数据
			}
			// 上传数据至后台服务器进行登录
			http.post('/user/login',dat)
			.then(data => {
				resolve(data)
			})
			.catch(fail => {
				console.log(fail);
				reject(fail)
			})
		})
		.catch(error => {
			reject(error)
		})
	})
}

function updateUserInfo(user){
	return http.post('/user/updateUserInfo',user)
}

// 获取微信code
function WeiXinGetCode(){
	uni.login({
	  provider: 'weixin',
	  onlyAuthorize: true,
	  success: (res) => {
		// console.log(res.code);
		store.commit('updateCode',res.code)
	  }
	})
}

// 微信请求登录
function WeiXinRequestLogin(){
	return new Promise((resolve, reject) => {
		uni.showModal({
			title:'提示',
			content:'将获取您的用户信息',
			confirmText:'同意',
			cancelText:'稍等',
			success: (res) => {
				if (res.confirm) {
					uni.showLoading({
						title:'',
						mask:true
					})
					uni.getUserProfile ({
					  desc: '用于登录使用',
					  success: (res) => {
						resolve(res);
					  }, 
					  fail: (error) => {
					    reject(error)
					  },
					  complete(res) {
					    uni.hideLoading()
					  }
					})
				}
			}
		})
	});
}

export{
	login,
	WeiXinGetCode,
	updateUserInfo
}